package org.roulette.generator;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.roulette.exception.IllegalInputException;

/**
 *
 * @author amra
 */
public class StaticNumberGenerator implements NumberGenerator{

	int pointer = 0;

	List<Integer> numbers = new ArrayList<Integer>(1000);

	public StaticNumberGenerator(String parrent, String filename) throws IOException, IllegalInputException{
		init(parrent, filename);
	}

	public StaticNumberGenerator(File file) throws IOException, IllegalInputException{
		init(file);
	}

	public StaticNumberGenerator(String content) throws IllegalInputException{
		init(content);
	}

	private void init(String parrent, String filename)throws IOException, IllegalInputException{
		File file = new File(parrent, filename);
		init(file);
	}

	private void init(File file)throws IOException, IllegalInputException{
		String content = loadContentFromFile(file);
		init(content);
	}

	private void init(String content) throws IllegalInputException{
		parseContent(content);
	}

	private String loadContentFromFile(File file) throws IOException{
		String result = "";
		try {
			result = FileUtils.readFileToString(file);
		} catch (IOException ex) {
			throw new IOException("Cannot load content from file: "+ex.getMessage(), ex);
		}
		return result;
	}

	private void parseContent(String content) throws IllegalInputException{
		for(String stringNumber: content.split(",")){
			try{
				Integer temp = Integer.valueOf(stringNumber.trim());
				numbers.add(temp);
			}
			catch(Exception e){
				throw new IllegalInputException("Cannot parse input data: '"+stringNumber+"'.", e);
			}
		}
	}

	public int generateNumber() {
		if(isNextNumber())
			return numbers.get(pointer++);
		else
			throw new IndexOutOfBoundsException("Index out of range.");
	}

	public void setRange(int rangeStart, int rangeEnd) {
//		throw new UnsupportedOperationException("Not supported yet.");
	}

	public boolean isNextNumber() {
		return pointer < numbers.size();
	}
}
